package com.bml.architect.netty.serialiable;

import com.bml.architect.netty.base.NettyClientHandler;
import com.bml.architect.netty.serialiable.codec.MsgProtoDecoder;
import com.bml.architect.netty.serialiable.codec.MsgProtoEncoder;
import com.bml.architect.netty.serialiable.codec.ProtostuffDecoder;
import com.bml.architect.netty.serialiable.codec.ProtostuffEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

public class NettySerialClient {

    public static void main(String[] args) {
        EventLoopGroup clientGoup = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(clientGoup)
                    .channel(NioSocketChannel.class)// 使用 NioSocketChannel 作为客户端的通道实现
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
//                            pipeline.addLast(new ObjectDecoder(10240, ClassResolvers.cacheDisabled(null)));
//                            pipeline.addLast(new ObjectEncoder());
                           // pipeline.addLast(new ProtostuffDecoder());
                           // pipeline.addLast(new ProtostuffEncoder());
                            pipeline.addLast(new MsgProtoEncoder());
                            pipeline.addLast(new MsgProtoDecoder());
                            pipeline.addLast(new SerialClientHandler());
                        }
                    });

            //启动客户端去连接服务器端
            System.out.println("客户端启动完成...");

            ChannelFuture cf = bootstrap.connect("127.0.0.1", 9000).sync();
            //对关闭通道进行监听
            cf.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            clientGoup.shutdownGracefully();
        }
    }
}
